import { CellDef, ColumnInput, RowInput, Styles } from "jspdf-autotable"
import { PDFTableOption } from "./type"

const RowStyles: Partial<Styles> = {
  valign: 'middle', 
  cellPadding: { left: 10, right: 10 },
  fontSize: 12
}

const HeadStyles: Partial<Styles> = {
  fontSize: 12
}

/**
 * 构建body
 * @param config 
 * @returns 
 */
export function createBody(config: PDFTableOption) {
  const body = [] as RowInput[]
  config.data.forEach((row, index) => {
    const tableRowList = [] as CellDef[]
    config.headers.forEach(h => {
      if(!h.rowSpan) {
        tableRowList.push({
          content: row[h.prop],
          styles: RowStyles,
        })
      } else {
        if(index === 0 || config.data[index - 1][h.prop] !== row[h.prop]) {
          const span = config.data.filter(r => r[h.prop] === row[h.prop]).length
          tableRowList.push({
            rowSpan: span,
            content: row[h.prop],
            styles: RowStyles,
          })
        }
      }
    })
    body.push(tableRowList)
  })

  return body
}

export function createColumns(config: PDFTableOption): ColumnInput[] {
  return config.headers.map(item => ({ 
    dataKey: item.prop, 
    header: {
      styles: HeadStyles,
      content: item.label
    },
  }))
}
